<?php
/**
 * Created by PhpStorm.
 * User: wzy12
 * Date: 2018/9/26
 * Time: 15:48
 */

namespace app\admin\model;


use think\Model;
use app\admin\validate\Goods as Vali;

class Goods extends Model
{
    /**
     * 商品分类
     * @return \think\model\relation\HasOne
     */
    public function cate(){
        return $this -> hasOne('GoodsCate', 'id', 'cate_id') -> field('cate_name');
    }

    public function resList($where){
        $query = $this -> where(1);

        // 筛选条件
        $is_where = $where;
        unset($is_where['page']);
        if($is_where) {
            if ($where) {
                // 查询商品上架和下架
                if ($where['is_on_sale'] || $where['is_on_sale'] === '0') {
                    $query->where('is_on_sale', $where['is_on_sale']);
                }
                // 查询商品标题，模糊查询
                if ($where['goods_name']) {
                    $query->where('goods_name', 'like', "%{$where['goods_name']}%");
                }
                // 查询商品分类
                if ($where['cate_id']) {
                    $query->where('cate_id', $where['cate_id']);
                }
                // 查询商品类型，是否为积分商品
                if ($where['exchange_integral']) {
                    $query->where('exchange_integral', $where['exchange_integral'], 0);
                }
            }
        }

        $list = $query -> order('sort desc,id desc') -> paginate(10, false, ['query'=>request()->param()]);
        foreach($list as $k => $v){
            $list[$k]['cate_name'] = $v -> cate -> cate_name;
        }

        $goods_cate = [];
        model('GoodsCate') -> chunk(100, function($item) use(&$goods_cate){
            // 将汉字的首字母拼音输出
            foreach($item as $k => $v){
                $item[$k]['cate_name'] = getFirstCharter($v['cate_name']) . '  ' . $v['cate_name'];
                $goods_cate[] = $item[$k];
            }
        });

        // 根据数组中cate_name的值首字母进行排序
        $cate_name = [];
        foreach ($goods_cate as $k => $v) {
            $cate_name[] = $v['cate_name'];
        }
        array_multisort($cate_name, SORT_ASC, $goods_cate);

        $arr['list'] = $list;
        $arr['goods_cate'] = $goods_cate;

        return $arr;
    }

    public function resFind($id){
        $result = $this -> find($id);

        // 商品属性和规格
        $result['goods'] = $this -> specAttr($result['model_id']);

        // 商品属性
        $arr = [];
        $attr = model('GoodsAttrValue') -> where('goods_id', $id) -> select();
        foreach($result['goods']['attr'] as $k => $v){
            $temp = explode("\n", $v['attr_value']);
            $arr[$k]['attr_value'] = $temp;
            $str = '';
            foreach($attr as $key => $val){
                if($v['id'] == $val['attr_id']){
                    $str = $val['attr_value'];
                }
            }
            $arr[$k]['input_value'] = $str;
            array_push($arr[$k], $result['goods']['attr'][$k]);
        }
        $result['attr'] = $arr;

        // 商品规格
        $list = $result['goods']['spec'];
        $spec = model('GoodsSpecImg') -> where('goods_id', $id) -> select();
        foreach($result['goods']['spec'] as $k => $v){
            foreach($v as $key => $val){
                foreach($spec as $k1 => $v1){
                    if($val['id'] == $v1['spec_item_id']){
                        $list[$k][$key]['checked'] = true;
                        $list[$k][$key]['img'] = $v1['img'];
                    }
                }
            }
        }
        $result['spec'] = $list;

        // 商品规格价格
        $specPrice = model('GoodsSpecPrice') -> where('goods_id', $id) -> select();
        $result['specPrice'] = json_encode($specPrice);

        return $result;
    }

    public function operation($data){
        $query = $this -> where(1);
        $action = false;
        if(isset($data['id'])){
            $action = true;
            $data['last_update'] = time();

            $status = $this -> where('id', $data['id']) -> value('is_on_sale');
            if($status == 1){
                return echoArr(1, '商品已上架，不允许进行更改');
            }

            $query -> where('id', '<>', $data['id']);
        }

        // 判断是否已有该商品
        $query -> where('goods_name', $data['goods_name']);
        $res = $query -> value('id');
        if($res){
            return echoArr(0, '商品名重复，请更改');
        }

        // 商品编号
        $id = $this -> order('id desc') -> value('id');
        $id += 1;
        $id = str_pad(isset($data['id']) ? $data['id'] : $id, 8, '0', STR_PAD_LEFT );
        $goods_sn = "SD$id";
        if(!$data['goods_sn']) {
            $data['goods_sn'] = $goods_sn;
            if(!isset($data['id'])){
                $res = $this->where('goods_sn', $data['goods_sn'])->value('id');
                if ($res) {
                    return echoArr(0, '你是不是将其他商品的货号改成系统货号');
                }
            }
        }else{
            $is_goods_sn = true;
            if(isset($data['id'])){

                $old_goods_sn = $this -> where('id', $data['id']) -> value('goods_sn');

                if($old_goods_sn == $data['goods_sn']){
                    $is_goods_sn = false;
                }
            }

            $res = $this->where('goods_sn', $data['goods_sn'])->value('id');
            if ($res && $is_goods_sn) {
                return echoArr(0, '商品货号重复');
            }
        }

        // 默认包邮
        if(!isset($data['is_free_shipping'])){
            $data['is_free_shipping'] = 0;

            if(!$data['template_id']){
                return echoArr(0, '请选择运费模板');
            }
        }else{
            unset($data['template_id']);
        }

        // 商品分类
        if(isset($data['cate_id'])){
            $data['cate_id'] = explode('-', $data['cate_id'])[0];
        }

        // 市场价
        if($data['shop_price'] > $data['market_price']){
            return echoArr(0, '商品售价不能大于市场价');
        }

        // 成本价
        if($data['cost_price'] > $data['shop_price']){
            return echoArr(0, '成本价不能大于商品售价');
        }

        // 验证
        $validate = new Vali();
        if(!$validate -> scene('form') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        // 添加商品
        $result = $this -> allowField(true) -> isUpdate($action) -> save($data);

        // 添加商品属性和规格处理
        if(!isset($data['id'])){
            $data['id'] = $this -> id;
        }else{
            // 删除商品属性和规格
            model('GoodsAttrValue') -> where('goods_id', $data['id']) -> delete();
            model('GoodsSpecImg') -> where('goods_id', $data['id']) -> delete();

            // 删除商品的规格价格
            model('GoodsSpecPrice') -> where('goods_id', $data['id']) -> delete();

            // 删除商品的图片
            model('GoodsImg') -> where('goods_id', $data['id']) -> delete();
        }

        // 添加商品属性
        if(isset($data['attr_value'])){
            $temp = [];
            foreach($data['attr_value'] as $k => $v){
                if(trim($v) != ''){
                    $arr = ['attr_id' => $k, 'goods_id' => $data['id'], 'attr_value' => $v];
                    $temp[] = $arr;
                }
            }
            $resAttr = model('GoodsAttrValue') -> allowField(true) -> saveAll($temp);
        }

        // 添加商品规格
        if(isset($data['spec_item'])){
            $temp = [];
            foreach($data['spec_item'] as $k => $v){
                if(isset($v['item'])){
                    foreach($v['item'] as $k1 => $v1){
                        $arr = ['goods_id' => $data['id'], 'spec_item_id' => $v1];
                        if(trim($v['img'][$v1])){
                            $arr['img'] = $v['img'][$k1];
                        }
                        $temp[] = $arr;
                    }
                }
            }
            $resSpecImg = model('GoodsSpecImg') -> allowField(true) -> saveAll($temp);
        }

        // 添加商品属性
        if(isset($data['group_img'])){
            $temp = [];
            foreach($data['group_img'] as $k => $v){
                $arr = ['goods_id' => $data['id'], 'img' => $v];
                $temp[] = $arr;
            }
            $resAttr = model('GoodsImg') -> allowField(true) -> saveAll($temp);
        }

        // 添加商品的规格价格
        if(isset($data['key'])){
            $temp = [];
            foreach($data['key'] as $k => $v){
                $status = 0;
                if(isset($v['status'])){
                    $status = 1;
                }

                $arr = ['key' => $k, 'goods_id' => $data['id'], 'price' => $v['price'], 'store' => $v['store'], 'status' => $status, 'key_name' => $v['key_name']];
                $temp[] = $arr;
            }
            $resSpecPrice = model('GoodsSpecPrice') -> allowField(true) -> saveAll($temp);
        }

        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }

    /**
     * 模型对应的属性规格值
     */
    public function specAttr($model_id){
        $result['attr'] =  model('GoodsAttr') -> where('model_id', $model_id) -> select();
        $spec = model('GoodsSpec')
            -> alias('s')
            -> where('s.model_id', $model_id)
            -> join('GoodsSpecItem i', 'i.spec_id = s.id')
            -> select();

        $arr = [];
        foreach ($spec as $data) {
            isset($arr[$data['spec_id']]) || $arr[$data['spec_id']] = array();
            $arr[$data['spec_id']][] = $data;
        }
        $result['spec'] = $arr;

        return $result;
    }

    /**
     * 更改排序
     */
    public function editSort($data){
        // 验证
        $validate = new Vali();
        if(!$validate -> scene('sort') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        $result = $this -> allowField(true) -> isUpdate(true) -> save($data);

        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '更新成功');
        }
    }

    /**
     * 更改状态
     */
    public function editStatus($data){
        // 判断是否更改上/下架
        if(!isset($data['is_on_sale'])){
            $status = $this -> where('id', $data['id']) -> value('is_on_sale');
            if($status == 1){
                return echoArr(0, '商品已上架，不允许进行更改');
            }
        }

        $data['on_time'] = time();

        // 验证
        $validate = new Vali();
        if(!$validate -> scene('status') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        $result = $this -> allowField(true) -> isUpdate(true) -> save($data);

        if(false === $result){
            return echoArr(0, $this -> getError());
        }else{
            return echoArr(1, '操作成功');
        }
    }

    /**
     * 展示分类信息
     */
    public function resCate(){
        $cate = cateList(model('GoodsCate') -> field('id,cate_name,pid') -> select() -> toArray());

        $temp = [];
        foreach($cate as $k => $v){
            $temp[$v['level']][] = $v;
        }

        return json_encode($temp);
    }

    /**
     * 商品删除
     */
    public function del($data){
        // 验证
        $validate = new Vali();
        if(!$validate -> scene('del') -> check($data)){
            return echoArr(0, $validate->getError());
        }

        // 判断商品是否上架
        $is_on_sale = $this -> whereIn('id', $data['id']) -> where('is_on_sale', 1) -> value('is_on_sale');
        if($is_on_sale == 1){
            return echoArr(0, '商品已上架，不允许删除该商品');
        }

        // 判断订单内是否有该商品
        $order_goods = model('OrderGoods') -> whereIn('goods_id', $data['id']) -> find();
        if($order_goods){
            return echoArr(0, "ID为【{$order_goods['goods_id']}】的商品有订单，不允许删除");
        }

        // 删除与商品关联的属性和规格
        $res_attr = model('GoodsAttrValue') -> whereIn('goods_id', $data['id']) -> delete();
        $res_spec = model('GoodsSpecImg') -> whereIn('goods_id', $data['id']) -> delete();
        $res_spec_price = model('GoodsSpecPrice') -> whereIn('goods_id', $data['id']) -> delete();

        // 删除与商品关联的图片
        $res_img = model('GoodsImg') -> whereIn('goods_id', $data['id']) -> delete();

        // 删除商品
        $result = $this -> destroy($data['id']);

        if(false === $result){
            return echoArr(0, '删除失败');
        }else{
            return echoArr(1, '删除成功');
        }
    }
}